local skynet = require "skynet"
local skynet_manager = require "skynet.manager"
local runconfig = require "runconfig"
local cluster = require "skynet.cluster"

skynet.start(function()
    -- 初始化
    local mynode = skynet.getenv("node")
    local nodecfg = runconfig[mynode]
    -- 节点管理
    -- local nodemgr = skynet.newservice("nodemgr", "nodemgr", 0)
    -- skynet.name("nodemgr", nodemgr)
    -- 集群
    cluster.reload(runconfig.cluster)
    cluster.open(mynode)

    -- login
    for i, v in pairs(nodecfg.login or {}) do
        local srv = skynet.newservice("login", "login", i)
        skynet.name("login" .. i, srv)
    end
    -- agentmgr
    local anode = runconfig.agentmgr.node
    if mynode == anode then
        local srv = skynet.newservice("agent_mgr", "agent_mgr", 0)
        skynet.name("agent_mgr", srv)
    else
        local proxy = cluster.proxy(anode, "agent_mgr")
        skynet.name("agent_mgr", proxy)
    end

    -- scenemgr
    local snode = runconfig.scenemgr.node
    if mynode == snode then
        local srv = skynet.newservice("scene_mgr", "scene_mgr", 0)
        skynet.name("scene_mgr", srv)
    else
        local proxy = cluster.proxy(snode, "scene_mgr")
        skynet.name("scene_mgr", proxy)
    end

    -- admin
    local admin_node = "node1" -- 读runconfig配置
    if mynode == anode then
        skynet.newservice("admin", "admin", 0)
    end

    local mysql_node = skynet.newservice("mysql", "mysql", 0)
    skynet.name("mysql_node", mysql_node)

    local register = skynet.newservice("register", "register", 0)
    skynet.name("register", register)

    skynet.newservice("debug_console", "127.0.0.1", "9666")

    -- gate
    for i, v in pairs(nodecfg.gateway or {}) do
        local srv = skynet.newservice("gateway", "gateway", i)
        skynet.name("gateway" .. i, srv)
    end

    -- 退出自身
    skynet.exit()
end)
